package org.example.demo;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.servlet.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/sensitive")
public class SensitiveServlet extends HttpServlet {
    private static final ObjectMapper M = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //验证用户身份：（1）获取session（获取不到不能创建）（2）验证session和其中的user
        HttpSession session = req.getSession(false);
        if(session != null){
            User user = (User) session.getAttribute("user");//这里的user要和登录保存的键一致
            if(user != null){//用户已登录
                //返回一些数据
                Map<String,Object> map = new HashMap<>();
                map.put("a", 1);
                map.put("b", "haha");
                map.put("c", true);
                resp.setContentType("application/json");
                resp.setCharacterEncoding("UTF-8");
                resp.getWriter().write(M.writeValueAsString(map));
                return;
            }
        }
        //其他情况，返回401状态码
        resp.setStatus(401);
    }
}
